﻿using System;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using Caliburn.Micro;
using Caliburn.Micro.Recipes.Filters.Framework;
using SS.Common.Logging;
using SS.WPF.Framework.Display.Dialog;
using SS.WPF.Framework.Display.MsgBox;
using SS.WPF.Framework.Display.MsgBox.ViewModels;
using SS.WPF.Framework.Localization;
using SS.WPF.Framework.Markup;
using SS.WPF.Framework.Preference;
using SS.WPF.Framework.ViewModel.Navigation;
using SS.WPF.Framework.ViewModel.Screen;
using TestFramework.Common;
using TestFramework.Config;

namespace TestFramework.ViewModels
{
    using System.ComponentModel.Composition;

    [Export(typeof (ScreenOneViewModel))]
    public class ScreenOneViewModel : EditorViewModelBase<NavigationNode>
    {
        private static readonly ILogger Logger = LoggerManager.GetLogger(typeof (ScreenOneViewModel).Name);

        private bool _isCheck = true;
        public bool IsChecked
        {
            get { return this._isCheck; }
            set
            {
                this._isCheck = value;
                this.NotifyOfPropertyChange(() => IsChecked);
            }
        }

        public string _displayLoginName = "LoginHere";
        public string DisplayLoginName
        {
            get { return this._displayLoginName; }
            set
            {
                this._displayLoginName = value;
                this.NotifyOfPropertyChange(() => DisplayLoginName);
            }
        }

        public string _userName = string.Empty;
        public string UserName
        {
            get { return this._userName; }
            set
            {
                this._userName = value;
                this.NotifyOfPropertyChange(() => UserName);
                this.NotifyOfPropertyChange(() => IsEnableLogin);
            }
        }

        public string _password = string.Empty;
        public string Password
        {
            get { return this._password; }
            set
            {
                this._password = value;
                this.NotifyOfPropertyChange(() => Password);
                this.NotifyOfPropertyChange(() => IsEnableLogin);
            }
        }

        public bool IsEnableLogin
        {
            get
            {
                return !string.Empty.Equals(UserName) && !string.Empty.Equals(Password);
            }
        }

        #region Using for DirtyChecker

        private bool _hasSystemListError;
        public bool HasSystemListError
        {
            get
            {
                return this._hasSystemListError;
            }
            set
            {
                this._hasSystemListError = value;
                this.HasError = this._hasSystemListError || HasGuiError;
            }
        }

        private bool _hasGuiError;
        public bool HasGuiError
        {
            get
            {
                return this._hasGuiError;
            }
            set
            {
                this._hasGuiError = value;
                this.HasError = this._hasGuiError || HasSystemListError;
            }
        }

        private IEnumerable _dirtyGroups;
        public IEnumerable DirtyGroups
        {
            get
            {
                return this._dirtyGroups;
            }
            set
            {
                this._dirtyGroups = value;
                this.NotifyOfPropertyChange(() => this.DirtyGroups);
            }
        }

        #endregion

        #region Implemetation of INotifyDirtyChanged

        private DemoCustomTypeDescriptor _systemSettingListList;

        public DemoCustomTypeDescriptor SystemSettingList
        {
            get
            {
                return this._systemSettingListList;
            }
            set
            {
                this._systemSettingListList = value;
                this.NotifyOfPropertyChange(() => this.SystemSettingList);
            }
        }

        #endregion

        public IPreferenceService PreferenceService
        {
            get
            {
                return IoC.Get<IPreferenceService>();
            }
        }

        public bool IsResetCheckboxEnabled
        {
            get
            {
                var pres = PreferenceService.GetPreferenceStore(typeof(MsgBoxViewModel).Name).GetAllValues();
                foreach (var preferenceInfo in pres)
                {
                    bool value;
                    if (Boolean.TryParse(preferenceInfo.ToString(), out value))
                    {
                        if (value)
                        {
                            return true;
                        }
                    }
                }
                return false;
            }
        }

        [Preview("IsResetCheckboxEnabled")]
        public IEnumerable<IResult> ResetCheckbox()
        {
            yield return this.BuildLongRun().Do(() =>
            {
                Logger.Info("ResetCheckbox");
                PreferenceService.GetPreferenceStore(typeof(MsgBoxViewModel).Name).Clear();
            });
        }

        protected override void OnInitialize()
        {
            this.PreferenceService.PreferenceChanged += new PreferenceChangedHandler(this.OnPreferenceChanged);
            this.SystemSettingList = new DemoCustomTypeDescriptor(new PropertySource());
            base.OnInitialize();
        }

        public void OnPreferenceChanged(string key, object newValue)
        {
            this.NotifyOfPropertyChange(() => IsResetCheckboxEnabled);
        }

        public void ChangeLanguage()
        {
            var name = this._isCheck ? "en" : "vi";
            IoC.Get<TranslationManager>().CurrentLanguage = IoC.Get<TranslationManager>().Languages
                .FirstOrDefault(x => x.TwoLetterISOLanguageName.Equals(name, StringComparison.OrdinalIgnoreCase));
        }

        [Preview("IsEnableLogin")]
        [Dependencies("UserName", "Password")]
        public IEnumerable<IResult> Login()
        {
            var result = this.DialogManager.ShowConfirmByKey("ConfirmLogin");
            if (result == MsgBoxResult.Yes)
            {
                var loginResult = LoginResult.Succeeded;

                // Start Authentication
                yield return this.BuildLongRun().Do(() =>
                {
                    loginResult = IoC.Get<ITaskManagerService>().Login(this._userName, this._password);
                })
                .BlockingUI()
                .Title(IoC.Get<TranslationManager>().Translate("LoggingIn").ToString());

                if (loginResult == LoginResult.Succeeded)
                {
                    yield return this.BuildShortRun().Do(() => this.DialogManager.ShowInfoByKey("LoginOK", string.Empty));
                }
                else
                {
                    yield return this.BuildShortRun().Do(() => this.DialogManager.ShowErrorByKey("LoginFailed", string.Empty));
                }
            }
        }
    }
}
